/**
 * 供应商基本信息前端模块
 * 
 * @Date: 2015-6-16
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(["jquery", "datagridServ","msgServ", "ajaxServ", "formServ", "sysmanMain","bizProto","btnServ","uploadfiles","panelUtil","buttonEvent"],
		function($,datagridServ, msgServ, ajaxServ, formServ,sysmanMain, bizProto,btnServ,uploadfiles,panelUtil,buttonEvent) {

			'use strict';

			var _bizProto,_buttonConfig,_moduleConfig,_defaultConfig,
				//锚记datagrid目标元素
				$dg,$typegrid,$detailgrid,
				//初始化后的datagrid dom对象
				$grid,
				//编辑弹窗对象及弹窗按钮对象
				$edit_window,window_btn,
				$edit_window_height=700,$edit_window_width=900,
				//设置密码弹窗对象及按钮对象
				$password_window,password_btn,
				//业务表单对象
				$form,selectedRecord,
				//部门选择框字段
				$deptNameField, $deptIdField,formEl, formData = 0,
				saveUrl = '/supplyBaseinfo/save.action',				
				typeid,
				detailEditUrl='/supplyBaseinfo/query/editPage.action',
				detailQryUrl='/supplyBaseinfo/query/getOne.action',
				editbtnSelector='td.edit-btn',
				
				//列表页面dom 根节点id
				rootid = 'div-supply-baseinfo',
				
				//基本信息页面根节点dom id
				baseInfoid='supply-baseinfo',
				archiveid = 'supply-archive',
				listid = 'supply-list-panel',
				//供应商查看详情初始条件
				initQueryParams
				

			var public_method = {
				
				/**
				 * 供应商查看详情初始化
				 */
				
				initDetail: function(_options){
					if (window.console) {
					console.info('supplyEdit modules supplyDetail function gets ready and been loaded.');
					}
					_moduleConfig = sysmanMain.getCurrentModuConfig();
					var _moduleConf = sysmanMain.getModuConf();
					_defaultConfig ={
						doc:null,
						rootId:null,				
						panelSelector:'div.well',
						subSystemCode:'sysman',
						edit_window:'win-doc-manage',
						moduleCode:'docdetail',
						upload_queue_id:null,
						upload_file_id:null,
						doccode:null,						
						initElement:null, //初始化扩展
						buttonExtends:null,//按钮扩展
						beforeSubmit:null,//提交前执行的数据处理函数
						editInitialized:false
					}
					
					_defaultConfig = $.extend({},_defaultConfig,_moduleConfig,_options)
					_buttonConfig={										    
						 "查看项目":private_method.queryItem,
						 "查看费用":private_method.queryFee,
						 "取消":public_method.cancel						 
					}
					
					_moduleConfig.buttonConfig = _buttonConfig
					var queryListUrl='/'+sysmanMain.getRootPath()+'/supplyBaseinfo/query/getOne.action'
					_bizProto = new bizProto(_defaultConfig);
					var _param = {
						height :_bizProto.gridHeight,
						url : _bizProto.queryListUrl,
						initQueryParams:{id:initQueryParams.id},
				//		toolbar:$(listTd),
						title:_defaultConfig.name
					}
					if(initQueryParams){
						ajaxServ.runAjax({
							url:queryListUrl,
							contentType:'form',
							data:initQueryParams,
							callback:public_method.initDataDetail})
					}
					
					
				},
				cancel : function() {
					//将初始条件清空
					initQueryParams=null;
					var $edit_window = $('#win-supply-detail-infomation');
					$($edit_window).window('close');
				},
				
				initDataDetail : function(data) {
					var record = data
					// 编辑窗口初始化	
					var k= $('#supply-inquiry-detailInfo');
					var f=k.find('form.main-form');
					$form=$(f)
					$form.form('clear')
					$form.form('load',record)
					/**
					 * 检查类型：根据类型数字判断对应的供应商类别
					 */
					if(record.id){							
						
						var _detailParam = {
							url :'/'+sysmanMain.getRootPath()+detailQryUrl,
							data:{id:record.id},
							type:'post',
							success:function(data){
								
								if($form.length==1){
									$($form).form('load',data);
								}
								
								var _typeid
								if(!data.integritytype){
									var $typegrid = $(domroot + " table.dg-type");
									_typeid = $($typegrid).treegrid('getSelected').id
								}else{
									_typeid = data.integritytype
								}
								var _typeElement = $($form).find("#integritytype")
								$(_typeElement).combobox({
									valueField:'id',
									textField:'text',
									data:[
										{id:'1',text:'药品'},
										{id:'2',text:'耗材'},
										{id:'3',text:'设备'},
										{id:'4',text:'其它'}
									],
									onSelect:function(recordText){
										var _typeNameElement = $($form).find("#integritytypeName")
										if(_typeNameElement.length==1){
											$(_typeNameElement).val(recordText.text)
										}
									}
								})
								$(_typeElement).combobox('select',_typeid)
							}
						}
						//查询业务记录
						$.ajax(_detailParam)
					}
					
					
					
					//绑定按钮事件					
					public_method.bindDataDetailBtnEvent();					
					
					//加载流程执行信息
									
				},
				
				//查看详情绑定事件绑定按钮事件
				bindDataDetailBtnEvent:function(){
					
					window_btn = $('#supply-inquiry-detailInfo').find('a.function-btn')
					$(window_btn).unbind('click')
					$(window_btn).bind('click',	private_method.function_btn_listenner)
					
				},
				
				openPage:function(_options){
					//定义参数配置信息
					initQueryParams = _options;
					var _defaultConfig = {
						rootId:'panel-supply-inquiry',
						subSystemCode:'supply',
						moduleCode:'supplyInquiry',						
						queryModule:null,
						queryMethod:null,
						width:900,
						height:700
					},
					supplyInquiryDetailInfoUrl='/supplyInquiry/query/supplyDetailPop.action',
					supplyInquiryDetailInfoWindow='#win-supply-detail-infomation',
					supplyInquiryDetailInfoWindowWith='900',
					supplyInquiryDetailInfoWindowHeight='700';
					$.extend(_defaultConfig,_options)
					var rootPath = '/'+sysmanMain.getRootPath();
					var _config = sysmanMain.getModuConf('supplyInquiry')
					if(!_config){
						_config = {}
					}
					$.extend(_config,_defaultConfig)
					sysmanMain.setModuConf('supplyInquiry',_config)
					var _param = {
						window:$(supplyInquiryDetailInfoWindow),
						href:rootPath + supplyInquiryDetailInfoUrl,
						width:_defaultConfig.width,
						height:_defaultConfig.height,
						onClose:private_method.onClose,
						flag:false}
					datagridServ.windowEdit(_param);	
				},
				openPage2:function(_options){
					//定义参数配置信息
					initQueryParams = _options;
					var _defaultConfig = {
						rootId:'supply-supplyInquiry-win',
						subSystemCode:'supply',
						moduleCode:'supplyInquiry',						
						queryModule:null,
						queryMethod:null,
						width:900,
						height:700
					},
					supplyInquiryDetailInfoUrl='/supplyInquiry/query/supplyDetailPop.action',
					supplyInquiryDetailInfoWindow='#win-supply-detail-infomation',
					supplyInquiryDetailInfoWindowWith='900',
					supplyInquiryDetailInfoWindowHeight='700';
					$.extend(_defaultConfig,_options)
					var rootPath = '/'+sysmanMain.getRootPath();
					var _config = sysmanMain.getModuConf('supplyInquiry')
					if(!_config){
						_config = {}
					}
					$.extend(_config,_defaultConfig)
					sysmanMain.setModuConf('supplyInquiry',_config)
					var _param = {
						window:$(supplyInquiryDetailInfoWindow),
						href:rootPath + supplyInquiryDetailInfoUrl,
						width:_defaultConfig.width,
						height:_defaultConfig.height,
						onClose:private_method.onClose,
						flag:false}
					datagridServ.windowEdit(_param);	
				},
				
				/**
				 * 
				 * @param _options.grid	  文档列表
				 * @param _options.flag	  新增或编辑标志
				 * @param _options.window	编辑窗口
				 * @param _options.typeid 分类id
				 */
				pageShow:function(_options){
					var _pageConfig = {
						width:$edit_window_width,
						height:$edit_window_height						
					}
					
					$.extend(_pageConfig,_options)
					
					var _url = '/'+sysmanMain.getRootPath() + detailEditUrl
										
					var _config = sysmanMain.getCurrentModuConfig();
					if(_config.addition_param){
						var _code = $.parseJSON(_config.addition_param)
						if(_code.moudle){
							_url = _url +'?module='+_code.moudle
						}
					}
					
					var _param = {
						grid:_options.grid,
						window:_options.window,
						href:_url,
						width:_pageConfig.width,
						height:_pageConfig.height,
						flag:_options.flag,
						existCheckElement:'form'			
					}
					if(_options.onClose){
						_param.onClose=_options.onClose
					}
					datagridServ.windowEdit(_param);
				},
				
				/**
				 * 
				 * @param _options.openid	  打开panel id值
				 * 
				 */
				toggleShow:function(_options){
					if(window.console){
						console.log(' toggleShow loaded and starting...')
					}
					var $panels = $('#'+ rootid +' div.toggle-panel' )					
					
					private_method.togglePanel({target:$listPanel})
					private_method.togglePanel({target:$formPanel})
				},
				buttonExtends:function(){
					var btnExtends = {}
					btnExtends ={
						'新增':function(e){
							private_method.togglePanel({openid:baseInfoid,type:'add',evt:e})
						},
						'基本信息':function(e){private_method.togglePanel({openid:baseInfoid,evt:e})},
						'资质文件':function(e){private_method.togglePanel({openid:archiveid,evt:e})},
						'附件':function(e){private_method.togglePanel({openid:'supply-archive',evt:e})},
						// '被授权人培训证':function(){private_method.togglePanel({bizcode:'supply-education',openid:'supply-archive'})},
						// '法人授权书':function(){private_method.togglePanel({bizcode:'supply-authorizeCertification',openid:'supply-archive'})},
						// '社保证明':function(){private_method.togglePanel({bizcode:'supply-socialsecurity',openid:'supply-archive'})},
						// '售后服务承诺书':function(){private_method.togglePanel({bizcode:'supply-aftersaleservice',openid:'supply-archive'})},
						// '不良记录':function(){private_method.togglePanel({openid:'supply-badinfomation'})},
						'批量提交':function(e){private_method.auditList({status:0,evt:e})},
						'批量审核':function(e){private_method.auditList({status:1,evt:e})},
						'批量退回':function(e){private_method.auditList({status:-1,evt:e})}
					}
					return btnExtends
				}
				
				
			}

			var private_method = {
				/**
				 * @param _options.openid
				 * @param _options.id
				 */
				

				togglePanel : function(_options) {

					_buttonConfig={
						
						"保存":function(e){private_method.submit(e)},
						"取消":private_method.cancel,
						"上传":private_method.upload,
						"附件":private_method.uploadInit,
						"删除":private_method.delupload,
						'提交审核':function(e){private_method.auditList({status:0,evt:e})},
						'审核通过':function(e){private_method.auditList({status:1,evt:e})},
						'审核未通过':function(e){private_method.auditList({status:-1,evt:e})},
						'返回列表':function(e){
							private_method.togglePanel({openid:listid})
							if(e && e.currentTarget){
								$(e.currentTarget).linkbutton('enable');
							}
						}

					}

					console.info("archiveid btn");

					if (_options.openid === archiveid) {
						console.info('this is archiveid\'s saveBtn');
						_buttonConfig = {
							"取消":private_method.cancel,
							"上传":private_method.upload,
							"附件":private_method.uploadInit,
							"删除":private_method.delupload,
							'提交审核':function(e){private_method.auditList({status:0,evt:_options.e})},
							'审核通过':function(e){private_method.auditList({status:1,evt:_options.e})},
							'审核未通过':function(e){private_method.auditList({status:-1,evt:_options.e})},
							'返回列表':function(e){
								private_method.togglePanel({openid:listid})
								if(e && e.currentTarget){
									$(e.currentTarget).linkbutton('enable');
								}
							}
						}

					}

					
						


					
					if(window.console){
						console.log(' togglePanel loaded and starting...')
					}
					var _queryParam = {}, _target
					//获取当前模块配置					
					
					var $panels = $('#'+ rootid +' div.toggle-panel' )
					if(_options.openid){
						_target = $('#'+ rootid + ' #' + _options.openid)
						if(_options.openid && _options.openid!=listid){
							
							//判断编辑和新增状态
							if(!_options.type || (_options.type!='add')){
								//确认只选择一条记录
								var selected = private_method.checkSelect()
								if(!selected){
									if(_options.evt && _options.evt.currentTarget){
										$(_options.evt.currentTarget).linkbutton('enable');
									}
									return 
								}else{
									_options.id=selected.id									
								}
							}
							
							var listHeight = $('#' + rootid + ' #' + listid).height()
							var listWidth = $('#' + rootid + ' #' + listid).width()
							$(_target).panel({height:listHeight,width:listWidth})
						}
					}
					if($panels.length>0 && _target.length>0){						
						$($panels).panel('close')						
						$(_target).panel('open')
						private_method.initPanel(_options)
					}
					
					if(_options.evt && _options.evt.currentTarget){
						$(_options.evt.currentTarget).linkbutton("enable")
					}
					
				},
				
				////
				
				/**
				 * 
				 * 批量审核
				 * @param _options.status	审核状态
				 * 
				 */ 
				auditList : function(_options) {
					if(window.console){
						
						console.log('del event fired ...')
					}
					var _config = sysmanMain.getCurrentModuConfig();
					var $detailgrid=$('#'+rootid+' table.dg-detail');
					console.info($detailgrid)
					_bizProto = _config.bizProto
					console.info(_bizProto.auditListUrl)
					datagridServ.auditList({url:_bizProto.auditListUrl,grid:$detailgrid,status:_options.status,evt:_options.evt});
					
				},
				
			
				/////
				
				
				checkSelect:function(){
					//判断是否选择了记录
					var $editBtn = $('#'+rootid + ' #' +baseInfoid + ' ' + editbtnSelector)
					var $grid = $('#'+rootid + ' #' +listid + ' table.dg-detail')
					if($grid.length==1){
						var selectRecords = $($grid).datagrid('getSelections')						
						if(!selectRecords || selectRecords.length<=0){
							msgServ.Msgslide('请先选择一条记录');
						}else{
							if(selectRecords.length>1){
								msgServ.Msgslide('选择了多条记录，无法执行当前操作');
							}else{								
								return selectRecords[0];
							}
						}										
						return 
						
					}
				},
				/**
				 * 初始化panel
				 * @param _options.openid
				 */
				initPanel:function(_options){
					//获取主记录id
					var mainid ,rootpath
					rootpath = '/' + sysmanMain.getRootPath();
					
					
					_options.rootpath=rootpath
					
					if(_options.openid){
						
						switch(_options.openid){
							case baseInfoid:
								private_method.initBaseInfo(_options)
							break;
							case archiveid:
								_options.buttonExtends={'返回列表':function(){private_method.togglePanel({openid:listid})}}
								private_method.uploadInit(_options)
								break;
							
							case 'supply-badinfomation':								
//								private_method.uploadInit(_options)
								break;
							default:
							break;
						}
					
					}
				},
				
				/**
				 * 初始化基本信息
				 * @param _options.openid	主记录id
				 * @param _options.rootpath 根路径
				 * @param _options.id		记录id
				 */
				initBaseInfo:function(_options){
					
					var $form = $('#'+rootid + ' #' +baseInfoid + ' form.main-form')
					$($form).form('clear')
					//初始化按钮
					var $editBtn = $('#'+rootid + ' #' +baseInfoid + ' ' + editbtnSelector)
					
					var _fullBizcode = 'supply:baseinfo'
					if($editBtn && $editBtn.length>0){
						$($editBtn).empty()
						var _param = {
							bizcode:_fullBizcode,
							rootPath:_options.rootpath,
							container:$editBtn,
							callback:private_method.bindBtnEvent}
						btnServ.generateEditBtn(_param);
					}
					//判断主记录id是否存在
					if(_options.id){							
						
						var _detailParam = {
							url :_options.rootpath+detailQryUrl,
							data:{id:_options.id},
							type:'post',
							success:function(data){
								
								if($form.length==1){
									$($form).form('load',data);
								}
								
								var _typeid
								if(!data.integritytype){
								    var domroot='#'+rootid;
									var $typegrid = $(domroot + " table.dg-type");
									_typeid = $($typegrid).treegrid('getSelected').id
								}else{
									_typeid = data.integritytype
								}
								var _typeElement = $($form).find("#integritytype")
								$(_typeElement).combobox({
									valueField:'id',
									textField:'text',
									data:[
										{id:'1',text:'药品'},
										{id:'2',text:'耗材'},
										{id:'3',text:'设备'},
										{id:'4',text:'其它'}
									],
									onSelect:function(record){
										var _typeNameElement = $($form).find("#integritytypeName")
										if(_typeNameElement.length==1){
											$(_typeNameElement).val(record.text)
										}
									}
								})
								$(_typeElement).combobox('select',_typeid)
							}
						}
						//查询业务记录
						$.ajax(_detailParam)
					}
					
					
					
				},				
				
				/**
				 * 绑定按钮事件
				 * @param _options.openid
				 */
				bindBtnEvent:function(_options){
					
					window_btn = $('#' + rootid +' div.edit-panel a.function-btn')
					$(window_btn).unbind('click')
					$(window_btn).bind('click',	private_method.function_btn_listenner)
					
					var file_btn = $('#' + rootid +' a.file_upload_btn')
					$(file_btn).unbind('click')
					$(file_btn).bind('click',	private_method.function_btn_listenner)
				},				
				
				//功能按钮监听函数
				function_btn_listenner:function(e){					
					btnServ.applyButton({buttonEvt:e,buttonConfig:_buttonConfig})					
				},
				/**
				 * 初始化基本信息
				 * @param _options.mainid	主记录id
				 */
				initArchive:function(_options){
					
				},
				
				
				init : function(_options) {
					if (window.console) {
					console.info('supplyEdit modules gets ready and been loaded.');
					}
					_moduleConfig = sysmanMain.getCurrentModuConfig();
					
					
					_defaultConfig ={
						doc:null,
						rootId:null,				
						panelSelector:'div.well',
						subSystemCode:'sysman',
						edit_window:'win-doc-manage',
						moduleCode:'docdetail',
						upload_queue_id:null,
						upload_file_id:null,
						doccode:null,						
						initElement:null, //初始化扩展
						buttonExtends:null,//按钮扩展
						beforeSubmit:null,//提交前执行的数据处理函数
						editInitialized:false
					}
					
					_defaultConfig = $.extend({},_defaultConfig,_moduleConfig,_options)
					if(_defaultConfig.bizcode)
						_defaultConfig.moduleCode = _defaultConfig.bizcode
					//初始化模块配置					
					_bizProto = new bizProto(_defaultConfig);
					_bizProto.gridHeight -= 15	
					_defaultConfig.bizProto = _bizProto								
					
					//按钮设置
					
					if(_defaultConfig.buttonExtends){
						var _extends
						if($.isFunction(_defaultConfig.buttonExtends)){
						 	_extends = _defaultConfig.buttonExtends()
						}else{
							_extends = _defaultConfig.buttonExtends
						}
						$.extend(_buttonConfig,_extends)
					}
					
					if(!_defaultConfig.edit_window){
						_defaultConfig.edit_window = 'win-doc-manage'						
					}
					$edit_window = $('#'+ _defaultConfig.edit_window);
					_defaultConfig.buttonConfig = _buttonConfig
					_defaultConfig.editInitialized = true;
					sysmanMain.setCurrentModuConfig(_defaultConfig);
					private_method.initElement(_bizProto.pageDoc)
					
					
				},				
				
				/**
				 * 获取当前明细列表中选中记录
				 */
				getCurrentDetailRecord:function(){
					var _record
					var _tab = sysmanMain.getCurrentTab();
					var _grid = $(_tab).find("table.dg-detail");
					return $(_grid).datagrid('getSelected');
				},
				
				//初始化元素
				initElement:function(doc){
					var tab = sysmanMain.getCurrentTab();

					$typegrid = $(tab).find("table.dg-doctype");
					$grid = $(tab).find("table.dg-detail");
					// 编辑窗口初始化
					
										
					
					// 编辑窗口初始化
					_moduleConfig = sysmanMain.getCurrentModuConfig();
					
					$form = $($edit_window).find('form')
					
					var editTd = $($edit_window).find('div.edit-btn')
					if(editTd.length<=0){
						editTd = $(tab).find('div.edit-btn')
					}
					var _fullBizcode = _moduleConfig.fullBizcode;
					
					if(editTd.length>0){
						var _param = {
							bizcode:_fullBizcode,
							rootPath:_bizProto.rootPath,
							container:editTd,
							callback:private_method.bindBtnEvent}
						btnServ.generateEditBtn(_param);
					}
					
					
					
					selectedRecord=$grid.datagrid('getSelected');
					if(selectedRecord){
						$form.form('load',selectedRecord);							
					}
					
					//扩展初始化方法
					if(_moduleConfig.initElement){
						var initParam = {rootId:_moduleConfig.rootId,edit_window:_moduleConfig.edit_window}
						if(selectedRecord){
							initParam.record = selectedRecord
						}
						_moduleConfig.initElement(initParam)
					}		

				},
				
				
				/**
				 * 初始化附件上传
				 * @param _options.id	业务id
				 * @param _options.bizcode	业务编码
				 * @param _options.openid	dom根节点id
				 * @param _options.buttonExtends	按钮扩展
				 */
				uploadInit:function(_options){
				
					//参数判断
					if(!_options){
						msgServ.Msgslide('参数异常，请刷新页面重新处理');
						return						
					}
					//主键及编码判断
					if(!_options.id || !_options.bizcode){
						//执行保存
					}
					
					
					var rootpath = '/'+sysmanMain.getRootPath();
					var domid = rootid + ' #' +_options.openid
					
					
					var uploadParam 
					= {
						data:{
							bizno:_options.id,
							bizcode:'supply-undefined'
						},
						rootPath:rootpath,
						buttonExtends:_options.buttonExtends
						
					}
					//绑定事件
					private_method.bindBtnEvent()
					
					var uploadListParam =
						$.extend({},
							{biztableid:domid + ' div.table-archive',
							toolbarid:domid + ' div.archive-btn',
							isSupplyEditPage : true},
							uploadParam)
					uploadfiles.initList(uploadListParam)
						
					var uploadfileParam =
						$.extend({},uploadParam,{
							queue_id:domid + ' form.upload-form #queue',
							file_id:domid + ' form.upload-form #file_upload',
							rootid:domid
						})
							
					uploadfiles.init(uploadfileParam)
						
				
				},
				upload:function(e){
//					_moduleConfig = sysmanMain.getCurrentModuConfig();
//					var _record = private_method.getCurrentDetailRecord();
					var _param ={
						rootid:rootid +' #' + archiveid +' #file_upload'
					}
					uploadfiles.upload(_param)
					
					if(e &&　e.currentTarget){
						$(e.currentTarget).linkbutton('enable');
					}
					
				},				
				
				
				
				// 提交form
				submit : function(e) {
					
					var domroot = '#'+rootid 
					var $form = $(domroot + ' #' +baseInfoid + ' form.main-form')
					

//					
					var rootpath = '/' + sysmanMain.getRootPath()
					formServ.save({
						targetForm:$form,
						url:rootpath + saveUrl
					},e)					
					
				},				

				//
				cancel : function() {
					$($edit_window).window('close');
				},
				delupload:function(){
					_moduleConfig = sysmanMain.getCurrentModuConfig();
					if(_moduleConfig.edit_window)
						uploadfiles.del({
							biztableid:_moduleConfig.edit_window + ' div.table-archive',
							rootPath:_moduleConfig.bizProto.rootPath})
				}




			};

			
			return public_method;

		});